package org.cheetah.core.impl;

import org.cheetah.core.Service;
import org.cheetah.core.ServiceInvoker;
import org.cheetah.core.exchange.Exchange;
import org.cheetah.core.exchange.Message;

public class DefaultServiceInvoker implements ServiceInvoker {
	private Service service;

	public DefaultServiceInvoker(Service service) {
		this.service = service;
	}

	public Message deliver(Message in) throws Exception {
		Exchange exchange = new Exchange(in);

		service.process(exchange);

		if (exchange.hasFault()) {
			Throwable t = exchange.getFault();

			if (t instanceof Exception) {
				throw (Exception) t;
			} else if (t instanceof Error) {
				throw (Error) t;
			} else {
				throw new Exception(t);
			}
		}

		if (exchange.hasOut()) {
			return exchange.getOut();
		}

		return null;
	}
}
